<template>
  <div class="callback-page">
    <div class="callback-container">
      <div class="loading" v-if="loading">
        <div class="spinner"></div>
        <p>正在处理钉钉登录...</p>
      </div>
      
      <div class="success" v-else-if="success">
        <div class="success-icon">
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none">
            <path d="M9 12L11 14L15 10M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="#07C160" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
        <h2>登录成功！</h2>
        <p>欢迎回来，{{ userInfo?.nickname || '用户' }}</p>
        <button class="continue-btn" @click="goToHome">继续使用</button>
      </div>
      
      <div class="error" v-else>
        <div class="error-icon">
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none">
            <path d="M12 9V13M12 17H12.01M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="#FF4D4F" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
        <h2>登录失败</h2>
        <p>{{ errorMessage }}</p>
        <button class="retry-btn" @click="retryLogin">重新登录</button>
      </div>
    </div>
    
    <!-- 实名认证弹窗 -->
    <IdentityVerifyModal ref="verifyModal" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import IdentityVerifyModal from '../components/IdentityVerifyModal.vue'

const router = useRouter()
const route = useRoute()

const loading = ref(true)
const success = ref(false)
const errorMessage = ref('')
const userInfo = ref(null)
const verifyModal = ref(null)

onMounted(async () => {
  try {
    console.log('钉钉回调页面加载，查询参数:', route.query)
    
    // 检查是否是从后端重定向过来的成功回调
    const successParam = route.query.success as string
    const token = route.query.token as string
    const refreshToken = route.query.refresh_token as string
    const expiresIn = route.query.expires_in as string
    const userInfoParam = route.query.user_info as string
    
    console.log('解析的参数:', {
      success: successParam,
      token: token ? '已获取' : '未获取',
      refreshToken: refreshToken ? '已获取' : '未获取',
      expiresIn,
      userInfo: userInfoParam ? '已获取' : '未获取'
    })
    
    if (successParam === 'true' && token) {
      // 后端已经处理成功，直接保存数据
      success.value = true
      
      // 解析用户信息
      if (userInfoParam) {
        try {
          const decodedUserInfo = decodeURIComponent(userInfoParam)
          console.log('解码后的用户信息:', decodedUserInfo)
          userInfo.value = JSON.parse(decodedUserInfo)
          console.log('解析后的用户信息对象:', userInfo.value)
        } catch (e) {
          console.warn('解析用户信息失败:', e)
          userInfo.value = { nickname: '用户' }
        }
      } else {
        userInfo.value = { nickname: '用户' }
      }
      
      // 保存token到localStorage
      localStorage.setItem('dingtalk_token', token)
      localStorage.setItem('dingtalk_refresh_token', refreshToken || '')
      localStorage.setItem('dingtalk_expires_in', expiresIn || '1800')
      // 保存解码后的 JSON 字符串，而不是 URL 编码的字符串
      localStorage.setItem('user_info', JSON.stringify(userInfo.value || {}))
      localStorage.setItem('login_time', Date.now().toString())
      
      // 保存用户ID
      if (userInfo.value && userInfo.value.user_id) {
        localStorage.setItem('user_id', userInfo.value.user_id)
        console.log('用户ID已保存:', userInfo.value.user_id)
      }
      
      console.log('用户信息已保存到localStorage')
      
      // 检查是否需要显示实名认证弹窗
      const shouldShowVerify = checkIfShouldShowVerify()
      if (shouldShowVerify) {
        // 延迟显示弹窗，让用户看到成功信息
        setTimeout(() => {
          verifyModal.value?.show()
        }, 1500)
      } else {
        // 2秒后自动跳转到首页
        setTimeout(() => {
          goToHome()
        }, 2000)
      }
    } else {
      // 直接访问回调页面，显示错误
      console.error('回调参数验证失败:', route.query)
      throw new Error('无效的回调请求，请重新登录')
    }
  } catch (error) {
    console.error('钉钉登录失败:', error)
    errorMessage.value = error.message || '登录过程中发生错误'
    success.value = false
  } finally {
    loading.value = false
  }
})

// 检查是否需要显示实名认证弹窗
const checkIfShouldShowVerify = () => {
  // 检查用户是否已经完成实名认证
  const isVerified = localStorage.getItem('user_verified') === 'true'
  
  // 检查用户是否选择了"稍后再去"
  const remindLater = localStorage.getItem('verify_remind_later') === 'true'
  
  // 检查是否是首次登录（登录时间在最近5分钟内）
  const loginTime = localStorage.getItem('login_time')
  const isRecentLogin = loginTime && (Date.now() - parseInt(loginTime)) < 5 * 60 * 1000
  
  // 如果未认证且不是"稍后再去"且是最近登录，则显示弹窗
  return !isVerified && !remindLater && isRecentLogin
}

const goToHome = () => {
  router.push('/')
}

const retryLogin = () => {
  // 重新跳转到钉钉授权页面
  window.location.href = 'http://localhost:8000/user/dingtalk/auth'
}
</script>

<style scoped>
.callback-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  padding: 20px;
}

.callback-container {
  background: white;
  border-radius: 12px;
  padding: 40px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  max-width: 400px;
  width: 100%;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1890FF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.success, .error {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.success-icon, .error-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}

h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

p {
  margin: 0;
  font-size: 16px;
  color: #666;
  line-height: 1.5;
}

.continue-btn, .retry-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.continue-btn {
  background: linear-gradient(135deg, #40A9FF, #1890FF);
  color: white;
}

.continue-btn:hover {
  background: linear-gradient(135deg, #1890FF, #096DD9);
  transform: translateY(-1px);
}

.retry-btn {
  background: #FF4D4F;
  color: white;
}

.retry-btn:hover {
  background: #FF7875;
  transform: translateY(-1px);
}

@media (max-width: 480px) {
  .callback-container {
    padding: 30px 20px;
  }
  
  h2 {
    font-size: 20px;
  }
  
  p {
    font-size: 14px;
  }
}
</style>
